﻿@inherits AdminCompontentBase
<div class="d-flex justify-space-between">
    <span class="h5 emphasis--text">@AlarmHistory.AlarmRule.ProjectIdentity</span>
    <span class="body2 regular--text block-center">
        <SDateTimeRangeToolbar StartDateTime="_startTime" EndDateTime="_endTime" OnUpdate="OnDateTimeUpdateAsync" ShowQuickChange="false" />
        <DefaultTooltip Class="ml-1 mt-n1" Tooltip="@T("DataBoundaryPrompt")" />
    </span>
</div>
<div class="d-flex justify-space-between mt-2">
    <span class="body2 regular--text">@AlarmHistory.AlarmRule.AppIdentity</span>
    <span class="body2 regular--text">
        @AlarmHistory.AlarmRule.DisplayName  @(!string.IsNullOrEmpty(AlarmHistory.AlarmRule.ChartYAxisUnit) ? $"({AlarmHistory.AlarmRule.ChartYAxisUnit})" : "")
    </span>
</div>
<div class="d-flex align-center justify-center">
    <MECharts @ref="_chart" Option="_option" Width="Width" Height="Height" OnClick="HandleOnClick">
    </MECharts>
</div>

@code {
    [Parameter]
    public StringNumber Width { get; set; } = 761;

    [Parameter]
    public StringNumber Height { get; set; } = 219;

    [EditorRequired]
    [Parameter]
    public AlarmHistoryViewModel AlarmHistory { get; set; } = new();

    [Parameter]
    public EventCallback<AlarmRuleRecordListViewModel> OnClick { get; set; }

    protected override string? PageName { get; set; } = "AlarmChartBlock";

    private AlarmHistoryViewModel _alarmHistory = new();

    private DateTimeOffset? _startTime = null;

    private DateTimeOffset? _endTime = null;

    private object _option = new();

    private MECharts? _chart = null;

    private List<AlarmRuleRecordListViewModel> _alarmRuleRecords = new();

    AlarmRuleRecordService AlarmRuleRecordService => AlertCaller.AlarmRuleRecordService;

    protected override async Task OnParametersSetAsync()
    {
        if (_alarmHistory != AlarmHistory)
        {
            _alarmHistory = AlarmHistory;
            _startTime = null;
            _endTime = null;
            await LoadData();
        }
    }

    Task OnDateTimeUpdateAsync((DateTimeOffset?, DateTimeOffset?) args)
    {
        (_startTime, _endTime) = args;
        return LoadData();
    }

    private async Task LoadData()
    {
        var queryParam = new GetAlarmRuleRecordInputDto(500)
            {
                AlarmHistoryId = AlarmHistory.Id,
                StartTime = _startTime?.UtcDateTime,
                EndTime = _endTime?.UtcDateTime,
                IsTrigger = true
            };

        var dtos = (await AlarmRuleRecordService.GetListAsync(queryParam));

        var paginatedList = dtos?.Adapt<PaginatedListDto<AlarmRuleRecordListViewModel>>() ?? new();
        var records = paginatedList.Result;

        var legendData = new List<string>();

        foreach (var item in records)
        {
            foreach (var key in item.AggregateResult.Keys)
            {
                if (!legendData.Contains(key))
                {
                    legendData.Add(key);
                }
            }
        }

        var seriesData = legendData.Select(key =>
        {
            var data = records.Select(x =>
            {
                var val = x.AggregateResult.FirstOrDefault(x => x.Key == key).Value;
                return new List<object> { x.ExcuteTime.ToUnixTimeMilliseconds(), val, x.Id };
            });

            return new
            {
                Name = key,
                Type = "line",
                Stack = "Total",
                Data = data,
                AreaStyle = new
                {
                    Color = new
                    {
                        ColorStops = new[] { new { Offset = 0, Color = "#FDCDC5" }, new { Offset = 1, Color = "rgba(255, 236, 232, 0)" } },
                        Global = false,
                        Type = "linear",
                        X = 0,
                        X2 = 0,
                        Y = 0,
                        Y2 = 1
                    }
                },
                Smooth = true
            };
        });

        RenderCharts(legendData, seriesData);

        _alarmRuleRecords = records ?? new();
    }

    private void RenderCharts(List<string> legendData, object seriesData)
    {
        _option = new
        {
            Tooltip = new
            {
                Trigger = "axis",
            },
            Legend = new
            {
                Bottom = "0%",
                Icon = "roundRect",
                Data = legendData
            },
            Grid = new
            {
                Left = 0,
                Right = 10,
                Top = 40,
                Bottom = 30,
                ContainLabel = true
            },
            XAxis = new
            {
                Type = "time",
                BoundaryGap = false,
                AxisLine = new
                {
                    LineStyle = new
                    {
                        Color = "#FF5252"
                    }
                },
                AxisLabel = new
                {
                    Color = "#A3AED0"
                },
                AxisTick = new
                {
                    Show = false
                }
            },
            YAxis = new
            {
                Type = "value",
                SplitLine = new
                {
                    Show = true,
                    LineStyle = new
                    {
                        Type = "dashed"
                    }
                }
            },
            Series = seriesData
        };
    }

    private async Task HandleOnClick(EChartsEventArgs args)
    {
        var recordId = Guid.Parse(args.Value[2].ToString());
        var record = _alarmRuleRecords.FirstOrDefault(x => x.Id == recordId);

        if (record != null && OnClick.HasDelegate)
        {
            await OnClick.InvokeAsync(record);
        }
    }
}
